<template>
  <div>
    <div class="oh">
      <el-upload ref="upload" :accept="accept" :action="uploadUrl" :before-upload="handleBeforeUpload"
        :headers="headers" :on-success="handleOnSuccess" :show-file-list="false" :style="' width: ' +
          upWidth +
          '; height:' +
          upHeight +
          ';line-height :' +
          upLineHeight
          " :class="showBorder ? 'avatar-uploader' : 'avatar-uploader avator-noborder'
            ">
        <el-button v-if="showBtn" type="primary" size="mini">
          {{ btnText }}
        </el-button>
      </el-upload>
    </div>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";

import { compressImgNew } from "@/utils/picture";
export default {
  name: "FileUploadBig",
  props: {
    accept: {
      type: String,
      default: ".jpg,.jpeg,.png",
    },
    showFileList: {
      type: Boolean,
      default: false,
    },

    showBtn: {
      type: Boolean,
      default: false,
    },
    btnText: {
      type: String,
      default: "上传",
    },
    upWidth: {
      type: String,
      default: "100px",
    },
    upHeight: {
      type: String,
      default: "100px",
    },
    upLineHeight: {
      type: String,
      default: "100px",
    },
    showBorder: {
      type: Boolean,
      default: true,
    },

    bindIndex: {
      type: Number,
      default: -1,
    },

    showProgre: {
      type: Boolean,
      default: true,
    },

    // 上传文件大小限制(MB)
    fileSize: {
      type: Number,
      default: 5000,
    },
  },
  data() {
    return {
      headers: {
        Authorization: "Bearer " + getToken()
      },
      uploadUrl: process.env.VUE_APP_BASE_API + "/system/oss/uploadOBSFile", // 上传的图片服务器地

    };
  },
  created() { },
  methods: {

    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      let types = [
        "image/jpeg",
        "image/jpg",
        "image/png"
      ];
      const isImage = types.includes(file.type);
      if (isImage) {
        return compressImgNew(file, 0.2)
      }

      // this.$modal.loading("正在上传文件，请稍候...");
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          // this.$modal.closeLoading();
          return false;
        }
      }
      return true;
    },

    // 上传成功
    handleOnSuccess(res, file) {
      // this.$modal.closeLoading();
      if (res.code === 500) {
        if (res.msg != null && res.msg != '') {
          this.$modal.msg(res.msg)
        } else {
          this.$modal.msg("上传失败，请重新上传")
        }
      } else {
        if (this.bindIndex > -1) {
          this.$emit("getUpload", res.data, this.bindIndex);
        } else {
          this.$emit("getUpload", res.data);
        }
      }
    },
  },
};
</script>

<style>
.avator-noborder .el-upload {
  border: none;
  border-radius: 0;
}
</style>